package com.zhangfb95.crosschain.protocol.rpc;

import com.zhangfb95.crosschain.infra.util.AesUtil;
import com.zhangfb95.crosschain.infra.util.UuidUtil;
import lombok.Data;
import lombok.experimental.Accessors;

import java.util.Objects;

/**
 * @author zhangfubing
 * @since 2023/12/14
 */
@Data
@Accessors(chain = true)
public class RpcAuthHandler {

    private String userId;
    private String nonce;
    private String timestamp;

    public RpcAuthHandler(String userId) {
        this.userId = userId;
        this.nonce = UuidUtil.uuid();
        this.timestamp = String.valueOf(System.currentTimeMillis());
    }

    public RpcAuthHandler(String userId, String nonce, String timestamp) {
        this.userId = userId;
        this.nonce = nonce;
        this.timestamp = timestamp;
    }

    public String genAuthorization(String secret) {
        String content = this.userId + ":" + this.nonce + ":" + this.timestamp + ":" + secret;
        return AesUtil.encryptToString(content, AesUtil.DEFAULT_PWD);
    }

    public boolean verify(String secret, String authorization) {
        String generatedAuthorization = genAuthorization(secret);
        return Objects.equals(authorization, generatedAuthorization);
    }
}
